package com.bancomer.batch.validators.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bancomer.batch.Constants;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.ValidationResult;
import com.bancomer.batch.util.FilesWriter;
import com.bancomer.batch.validators.GeneralValidator;

public class OfficeTypeValidator implements GeneralValidator {
	private StringBuffer condition = new StringBuffer();
	private StringBuffer totalCondition = new StringBuffer();
	
	Logger logger = Logger.getLogger("OfficeTypeValidator");
	
	public ValidationResult getAmountByOffice(FileHelper inputFile,Alert alert){
		Map<String,String> amountFilter = new HashMap<String,String>();
		FileHelper parameterFile = null;
		ValidationResult result = new ValidationResult();
		FileReader input = null;
		BufferedReader buffer = null;
		
		String positionsLoad2;
		String namesLoad2;
		String[] columnsPositionsLoad2;
		String[] columnsNamesLoad2;
		String load2="";
	
		String line;
		Map<String,int[]> columnPositionsLoad2 = new HashMap<String, int[]>();
		
		try{
			for(FileHelper file : alert.getOutputFiles()){
				if(file.getName().equals("pigScriptParameters.properties")){
					parameterFile = file;
					break;
				}
			}
			input = new FileReader(parameterFile.getLocalPath()+parameterFile.getName());
			buffer = new BufferedReader(input);
			line=buffer.readLine();
			while(line!=null){
				if(line.contains(inputFile.getProperties().getProperty("layoutName"))){
					load2 = line.split("=")[1];
					break;
				}
				line = buffer.readLine();
			}
			buffer.close();
			load2 = load2.replace("com.bancomer.pig.functions.IndexOfLoader", "");
			load2 = load2.replaceAll("[\\(\\'\\ \\)]","");
			positionsLoad2 = load2.split("as")[0];
			namesLoad2 = load2.split("as")[1];
			columnsPositionsLoad2 = positionsLoad2.split(",");
			columnsNamesLoad2 = namesLoad2.split(",");
			
	
			for(int i=0;i<columnsPositionsLoad2.length;i++){
				int[] indexPositions = new int[2];
				indexPositions[0]=Integer.valueOf(columnsPositionsLoad2[i].split("-")[0]);
				indexPositions[1]=Integer.valueOf(columnsPositionsLoad2[i].split("-")[1]);
				columnPositionsLoad2.put(columnsNamesLoad2[i].split(":")[0],indexPositions);
			}
			input = new FileReader(inputFile.getLocalPath()+inputFile.getName());
			buffer = new BufferedReader(input);	
			line = buffer.readLine();
			while (line != null)   {
				result = doConditionAmount(line,columnPositionsLoad2);
				if(result.getSucces()==false){
						buffer.close();
						return result;
				}
				line = buffer.readLine();
		    }
		
			if("".equals(condition.toString().trim())){
				result.setMessage("No hay configuración de importe para la "+alert.getName()+ " en el archivo "+inputFile.getName());
				result.setSucces(false);
				buffer.close();
				return result;
			}
			condition.deleteCharAt(condition.length()-1);
			totalCondition.append("validateAmount(TRIM($12),$5,'"+condition.toString()+"') as (validador:int)");
			amountFilter.put("amountFilter", totalCondition.toString());
			FilesWriter.writePropertiesFile(parameterFile,amountFilter);
		}
		catch(Exception e){
			result.setMessage("Class: OfficeTypeValidator - "+e.getMessage());
			result.setSucces(false);
		}
		return result;
		
	}
	
	public ValidationResult doConditionAmount(String line,Map<String,int[]> columnPositionsLoad2){
		ValidationResult result = new ValidationResult();
		int[] indexPositionsLoad2;
		try {
			String aleIndicator = "";
			String alert06 = "";
			String concept = "";
			String operator = "";
			String officeType= "";
			String amount = "";
			indexPositionsLoad2 = columnPositionsLoad2.get(Constants.TAB_CS_COL1);
			aleIndicator = line.substring(indexPositionsLoad2[0],indexPositionsLoad2[1]);
			indexPositionsLoad2 = columnPositionsLoad2.get(Constants.TAB_CS_COL2);
			alert06 = line.substring(indexPositionsLoad2[0],indexPositionsLoad2[1]).trim();
			if(Constants.ALE.equals(aleIndicator.trim())&&Constants.ALERT_06.equals(alert06.trim())){
				indexPositionsLoad2 = columnPositionsLoad2.get(Constants.TAB_CS_COL5);
				concept = line.substring(indexPositionsLoad2[0],indexPositionsLoad2[1]).trim();
				if(Constants.CONCEPTO.equals(concept)){
					indexPositionsLoad2 = columnPositionsLoad2.get(Constants.TAB_CS_COL7);
					operator = line.substring(indexPositionsLoad2[0],indexPositionsLoad2[1]).trim();
					indexPositionsLoad2 = columnPositionsLoad2.get(Constants.TAB_CS_COL4);
					officeType = line.substring(indexPositionsLoad2[0],indexPositionsLoad2[1]).trim();
					indexPositionsLoad2 = columnPositionsLoad2.get(Constants.TAB_CS_COL8);
					amount = line.substring(indexPositionsLoad2[0],indexPositionsLoad2[1]).trim();
					if("".equals(operator.trim())||"=".equals(operator.trim())){
						operator="==";
					}
					condition.append(officeType+","+operator+","+amount+";");
				}
			}
		} catch (Exception e) {
			result.setMessage(e.getMessage());
			result.setSucces(false);
		}
		return result;
	}
	
	@Override
	public ValidationResult executeValidation(FileHelper fileHelper,
			Object... obj) {
		// TODO Auto-generated method stub
		ValidationResult result = new ValidationResult();
		try {
			result = getAmountByOffice(fileHelper,(Alert)obj[0]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setMessage(e.getMessage());
			result.setSucces(false);
		}
		return result;
	}
}
